<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets" style="margin-top: 5px"></i>
      <span style="margin-top: 5px">数据列表</span>
      <el-button
        class="btn-add"
        @click="handleAddProductCate()"
        size="mini">
        添加
      </el-button>

      <el-button
        class="btn-add"
        :disabled="multipleSelection.length<1"
        size="mini"
        type="danger"
        @click="multiDelete()">
              批量删除
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="productCateTable"
                style="width: 100%"
                 @selection-change="handleSelectionChange"
                :data="list" border>
        <el-table-column label="编号" width="100" align="center">
        <el-table-column type="selection" width="60" align="center"></el-table-column>

          <template slot-scope="scope">{{scope.row.ptid}}</template>
        </el-table-column>

        <el-table-column label="分类名称" align="center">
          <template slot-scope="scope">{{scope.row.ptype}}</template>
        </el-table-column>

         <el-table-column label="分类图标" width="200" align="center">
          <template slot-scope="scope"><img style="height: 80px;width:80px;" :src="imgUrl+'/image/'+scope.row.tppicture.tname"></template>
        </el-table-column>
        <!-- <el-table-column label="级别" width="100" align="center">
          <template slot-scope="scope">{{scope.row.level | levelFilter}}</template>
        </el-table-column>
        <el-table-column label="商品数量" width="100" align="center">
          <template slot-scope="scope">{{scope.row.productCount }}</template>
        </el-table-column>
        <el-table-column label="数量单位" width="100" align="center">
          <template slot-scope="scope">{{scope.row.productUnit }}</template>
        </el-table-column>
        <el-table-column label="导航栏" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleNavStatusChange(scope.$index, scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.navStatus">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否显示" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleShowStatusChange(scope.$index, scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.showStatus">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="100" align="center">
          <template slot-scope="scope">{{scope.row.sort }}</template>
        </el-table-column>
        <el-table-column label="设置" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :disabled="scope.row.level | disableNextLevel"
              @click="handleShowNextLevel(scope.$index, scope.row)">查看下级
            </el-button>
            <el-button
              size="mini"
              @click="handleTransferProduct(scope.$index, scope.row)">转移商品
            </el-button>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleUpdate(scope.row,1)">修改名称
            </el-button>
             <el-button
              size="mini"
              @click="handleUpdate(scope.row,2)">更换图标
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
       <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      @close="dialogClose"
      width="50%">
      <el-form ref="productCate" :model="productCate" :rules="rules" label-width="120px" >
        <el-form-item label="分类名称" prop="ptype" v-if="stutasEdit!=2">
          <el-input v-model="productCate.ptype" auto-complete="off"  @keyup.enter.native="handleConfirm('productCate')"></el-input>
        </el-form-item>
  <!-- 图片 -->
        <el-form-item label="图标" prop="sname" v-if="stutasEdit!=1" >

            <el-upload
              action="https://jsonplaceholder.typicode.com/posts/"
              list-type="picture-card"
              ref="upload"
              :on-preview="handlePictureCardPreview"
              :before-upload="beforeUpload"
              :on-change="handleChange"
              :auto-upload="false"
              :limit="limitCount"
              :file-list="imgFile"
              :on-remove="handleRemove"
             
              :class="{hide:hideUpload}">
              <i class="el-icon-plus"></i>
            </el-upload>

            <el-dialog :visible.sync="dialogShow">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>

        </el-form-item>

  <!-- 图片完 -->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('productCate')" >确 定</el-button>
      </span>
    </el-dialog>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pagesize"
        :page-sizes="[5,10,15]"
        :current-page.sync="listQuery.page"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  // import {fetchList,deleteProductCate,updateShowStatus,updateNavStatus} from '@/api/productCate'

import {fetchList,deleteProductCate,createProductCate,updateProductCate,updateProductImg} from '@/api/productCate'

  export default {
    name: "productCateList",
    data() {
      return {
        list: null,
        total: null,
        dialogVisible:false,
        isClientCertFile:true,
        multipleSelection:[],
        dialogTitle:'',
        stutasEdit:0,
        productCate:{
          ptype:'',
          ptid:null,
          tpid:null
        },
        hideUpload: false,
        limitCount:1,
        listQuery: {
          page: 1,
          pagesize: 10
        },
        parentId: 0,
        rules: {
            ptype: [
              { required: true, message: '请输入分类名称', trigger: 'blur' }
              
            ]
        },

        dialogImageUrl: '',
        dialogShow: false,
        disabled: false,
        imgFile:[],
        imgUrl:''

      }
    },

    created() {
      this.resetParentId();
      this.getList();
      process.env.NODE_ENV === 'development' ? this.imgUrl = '/api/' : this.imgUrl = process.env.API_ROOT ;
      // alert(this.imgUrl);
    },

    watch: {

      $route(route) {
        // this.resetParentId();
        this.getList(); 
      }

    },
    methods: {
       handleSelectionChange(val) {
          this.multipleSelection = val;
      },
       // 批量删除分类
      multiDelete(){
        let list = this.multipleSelection;
        let data=list.map((res)=>{
          return res.ptid
        })
        this.$confirm(`是否批量删除选中的${data.length}个分类`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProductCate({array:data}).then(response => {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1000
            });
            this.getList();
          });
        });
      },
      // 预览图片
      handlePictureCardPreview(file) {
        // alert(file.url);
        this.dialogImageUrl = file.url;
        this.dialogShow = true;
      },

      // 下载图片
      handleDownload(file) {
        console.log(file);
      },

       //值改变 判读是否有值
      handleChange(file, fileList, name) {
        console.log(this.imgFile);
        this.hideUpload = fileList.length >= this.limitCount;
        this.imgFile["file"] = fileList;
        if (typeof this.imgFile.file != "undefined" && this.imgFile.file.length > 0) {
          this.isClientCertFile = false;
        } else {
          this.isClientCertFile = true;
        }
      },

      //值被清空 
      handleRemove(file, fileList, name) {
        this.hideUpload = fileList.length >= this.limitCount;
        this.isClientCertFile = true;
      },

      dialogClose(){
        this.imgFile=[];
      },

      // 上传图片
      beforeUpload(file){
        this.$refs.upload.clearFiles();
        console.log(file);
        let _this = this;

          let param = new FormData()  // 创建form对象
          param.append('fileupload', file, file.name)  // file对象是 beforeUpload参数

          if(this.stutasEdit===0){
            param.append('ptype',_this.productCate.ptype);
             createProductCate(param).then(res=>{
              console.log(res);
              _this.$message({
                  message: '添加成功',
                  type: 'success',
                  duration:1000
                });
                _this.dialogVisible = false;
                _this.getList();
            })

          }else{
            param.append('tpid',_this.productCate.tpid);
              updateProductImg(param).then(res=>{
              console.log(res);
              _this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration:1000
                });
                _this.dialogVisible = false;
                _this.getList();
            })

          }

           
         

            return false
      },


    // 新增or编辑点击确定
      handleConfirm(formName){
        this.$refs[formName].validate((valid) => {
            console.log(this.isClientCertFile);

          if (valid) {
                 if(this.stutasEdit===1){
                      updateProductCate(this.productCate).then(res=>{
                        this.$message({
                          message: '修改成功',
                          type: 'success',
                          duration:1000
                        });
                          this.dialogVisible = false;
                          this.getList();
                      })
                      return
                }

                 if (this.isClientCertFile) {
                      this.$message.error("请选择图片作为分类图标")
                      return
                    }
                 console.log(this.$refs.upload);
                 this.$refs.upload.submit();

       // 上传
              // this.$refs.upload.submit();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetParentId(){
        this.listQuery.page = 1;
        if (this.$route.query.parentId != null) {
          this.parentId = this.$route.query.parentId;
        } else {
          this.parentId = 0;
        }
      },
      // 新增
      handleAddProductCate() {
        this.stutasEdit=0;
         this.dialogVisible = true;
         this.dialogTitle = "添加分类";
        this.productCate=Object.assign({},{ ptid:null,ptype:'',tpid:null});
      },
      // 查询
      getList() {
        fetchList(this.listQuery).then(response => {
          this.list = response.obj.list;
          this.total = response.obj.count;
        });
      },
      handleSizeChange(val) {
        this.listQuery.page = 1;
        this.listQuery.pagesize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
     
    
     
      // 编辑名称
      handleUpdate(row,i) {
        this.productCate=Object.assign({},{ ptid:null,ptype:'',tpid:null})
        this.dialogVisible = true;
          this.stutasEdit=i;
        if(i==1){
          this.dialogTitle = "编辑分类名称";
          // this.productCate.ptype = row.ptype;
          this.productCate.ptid = row.ptid;
        }else{
          this.dialogTitle = "修改分类图标";
          this.productCate.tpid = row.tpid;
        }
        
      },
      // 删除分类
      handleDelete(row) {
        this.$confirm('是否要删除该分类', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProductCate({array:[row.ptid]}).then(response => {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1000
            });
            this.getList();
          });
        });
      }
    },
    filters: {
      levelFilter(value) {
        if (value === 0) {
          return '一级';
        } else if (value === 1) {
          return '二级';
        }
      },
      disableNextLevel(value) {
        if (value === 0) {
          return false;
        } else {
          return true;
        }
      }
    }
  }
</script>

<style>
.hide .el-upload--picture-card {
    display: none;
}
</style>
